﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;

namespace DuBaiCoffee2.Model
{
    public class IceMakingMsg
    {
        private static IceMakingMsg instance;
        private IceMakingMsg() { }

        public static IceMakingMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new IceMakingMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        public bool RobotBol = true;
        public delegate void IOdelegate(string btnName, string tag);
        public IOdelegate iodelegate;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public int IceInit = 0;
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.ZBPortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                IceMakingSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.ZBPortName, 115200, "", 8, 1);//其他串口通讯
                IceMakingSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                //  AllMassage();
            }
            catch (Exception)
            {
                IceMakingSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(1000);
                IceInit++;
                if (IceInit == 20)
                {
                    EmailShow emailShow = new EmailShow();
                    emailShow.content = EmailError();
                    var saves1 = JsonConvert.SerializeObject(emailShow);
                    var dd1 = HttpMsg.Instance.sendEmailMsg(saves1);
                }
                IOSerial_Thr();
            }
        }
        public void AllMassage()
        {
            try
            {
                while (true)
                {
                    try
                    {
                        if (Instance.AllBol)
                        {
                            IceMakingSerialPort.Instance.SerialSend(IceMakingModel.Instance.AllMessage);
                            Console.WriteLine("zhibing");
                        }
                        Thread.Sleep(1000);
                    }
                    catch (Exception)
                    {
                        Thread.Sleep(1000);
                    }

                }
            }
            catch (Exception)
            {
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] result = new byte[IceMakingSerialPort.Instance.serialPort.BytesToRead];
                IceMakingSerialPort.Instance.serialPort.Read(result, 0, IceMakingSerialPort.Instance.serialPort.BytesToRead);
                string str = "";// $"{DateTime.Now}：\n";
                str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                //Console.WriteLine(str);
                MsgShow(str);
                Thread.Sleep(1);
            }
            catch (Exception)
            {
                return;
            }
        }
        string zblist = "";
        public bool ErrorBol = true;
        public bool ZBJBol = true;
        public void MsgShow(string str)
        {
            try
            {
                Console.WriteLine(str);
                var note = str.Split(' ');
                string note1 = "";
                #region 旧的
                if (note[0].Length >= 2)
                {
                    note1 = note[0].Substring(note[0].Length - 2, 2);
                }
                if (zblist.Length == 27)
                {
                    Console.WriteLine(zblist);
                    var dd = zblist.Split(' ');
                    if (dd.Count() == 9)
                    {
                        if (dd[4] != "00")
                        {

                            if (ErrorBol)
                            {
                                if (dd[4] == "06")
                                {
                                    EmailShow emailShow = new EmailShow();
                                    emailShow.content = EmailError();
                                    var saves1 = JsonConvert.SerializeObject(emailShow);
                                    var dd1 = HttpMsg.Instance.sendEmailMsg(saves1);
                                    ErrorBol = false;
                                    WuLiaoCoffeeSel.Instance.Ice1_Sel_Bol = false;
                                    ClientList clientList = new ClientList();
                                    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                                    clientList.code = 2;
                                    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                                    Console.WriteLine("制冰机报错");
                                    Console.WriteLine("制冰机报错");
                                }
                            }
                            else
                                Console.WriteLine("制冰机未满");
                            ZBJBol = false;
                        }
                        else
                        {
                            if (!ErrorBol)
                            {
                                WuLiaoCoffeeSel.Instance.Ice1_Sel_Bol = true;
                                ClientList clientList = new ClientList();
                                clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                                clientList.code = 2;
                                SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                            }
                            ErrorBol = true;
                            ZBJBol = true;
                        }
                    }

                    zblist = "";
                }
                if (note1 == "01")
                {
                    zblist = note1 + " ";
                }
                else if (zblist != "")
                    zblist += note1 + " ";
                if (zblist != "")
                {
                    if (note.Count() > 1)
                    {
                        for (int i = 1; i < note.Count(); i++)
                        {
                            if (note[i] != "")
                                zblist += note[i] + " ";
                        }
                    }
                }
                #endregion
                //  Console.WriteLine(zblist);

            }
            catch (Exception)
            {
                return;
            }
        }
        public static string EmailError()
        {
            try
            {
                string msg = "<style>table{ border: 1px solid black; border-collapse: collapse; }table td{border: 1px solid #000000; padding: 5px 15px;font-size:14px;}</style><table>";
                msg += "<tr><td style='font-weight:bold;'>ice machine</td><td style='color:#FF0000;'>equipment failure</td></tr>";
                msg += "</table>";
                return msg;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion
    }
}
